package com.freecloud.javabasics.thread.result;

import com.freecloud.common.LoggerUtil;

import java.util.concurrent.*;

/**
 * @Author: maomao
 * @Date: 2020-03-04 10:50
 */
public class CallableAndFutureTask {

    public static void main(String[] args) {
        ExecutorService executor = Executors.newCachedThreadPool();
        try {
            AccumulationTask task = new AccumulationTask(100);
            FutureTask<Integer> futureTask = new FutureTask(task);
            executor.submit(futureTask);
            System.out.println("task运行结果" + futureTask.get());
            executor.shutdown();

            LoggerUtil.split();
            LoggerUtil.println("主线程在执行任务");

        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("所有任务执行完毕");
    }

    static class AccumulationTask implements Callable<Integer> {

        private Integer num;

        public AccumulationTask(Integer num){
            this.num = num;
        }

        @Override
        public Integer call() throws Exception {
            LoggerUtil.split();
            LoggerUtil.printThread();
            LoggerUtil.println("子线程在进行计算");
            Thread.sleep(3000);
            int sum = 0;
            for (int i = 0; i < num; i++) {
                sum++;
            }
            LoggerUtil.println("子线程在计算完成");
            Thread.sleep(3000);
            return sum;
        }
    }
}
